package org.example.springcache2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;

import java.util.Collection;
import java.util.Map;

@EnableCaching
@SpringBootApplication
public class SpringCache2Application implements CommandLineRunner {
    @Autowired
    StatusRepository statusRepository;

    @Autowired
    StatusService statusService;
    
    @Autowired
    CacheManager cacheManager;

    public static void main(String[] args) {
        SpringApplication.run(SpringCache2Application.class, args);
    }

    public void printAllCache(){
        Collection<String> cacheNames = cacheManager.getCacheNames();
        for (String name : cacheNames) {
            Cache cache = cacheManager.getCache(name);
            Map<Object,Object> allCache = (Map<Object, Object>) cache.getNativeCache();
            for (Object k: allCache.keySet()) {
                System.out.printf("cacheName: %s, key: %s, value: %s\n",name, k.toString(), allCache.get(k));
            }
        }
        System.out.println("-------------------------------------------------------");
    }
    
    @Override
    public void run(String... args) throws Exception {
        Status status = new Status();
        status.setContent("First blog");
        status.setAuthor("Peter");
        status.setLikes(11);
        statusRepository.save(status);

        statusService.getStatus(status.getId());
//        缓存命中
        statusService.getStatus(status.getId());

        statusService.countStatus("Peter");
//        缓存命中
        statusService.countStatus("PETER");

        statusService.getHotStatus(10);
//        缓存命中
        statusService.getHotStatus(10);

        status.setContent("First modified blog");
        statusService.updateStatus(status);
        System.out.println(statusService.getStatus(status.getId()));

        statusService.evictHotStatus();
//        缓存命中
        statusService.getHotStatus(10);

        printAllCache();
        statusService.removeStatus(status.getId());
    }
}
